#include "CountdownWidget.h"

#include <QMessageBox>
#include <QFont>

CountdownWidget::CountdownWidget(int seconds)
{
    inputEdit = std::make_shared<QLineEdit>(this);
    inputEdit->setText(std::to_string(seconds).c_str());

    startButton = std::make_shared<QPushButton>("开始", this);
    connect(startButton.get(), &QPushButton::clicked, this, &CountdownWidget::startCountdown);

    QFont font;
    font.setPointSize(20);
    font.setBold(true);
    countdownLabel = std::make_shared<QLabel>(this);
    countdownLabel->setFont(font);
    countdownLabel->setText("0");

    countdownTimer = std::make_shared<QTimer>(this);
    connect(countdownTimer.get(), &QTimer::timeout, this, &CountdownWidget::updateCountdown);

    mainLayout = std::make_shared<QVBoxLayout>();
    inputLayout = std::make_shared<QHBoxLayout>();


    inputLayout->addWidget(inputEdit.get());
    inputLayout->addWidget(startButton.get());

    mainLayout->addLayout(inputLayout.get());
    mainLayout->addWidget(countdownLabel.get());

    setLayout(mainLayout.get());
}

CountdownWidget::CountdownWidget(std::shared_ptr<QWidget> parent, int secdonds) :CountdownWidget(secdonds){
    startButton->installEventFilter(parent.get());
}

 CountdownWidget::CountdownWidget(QWidget* parent, int secdonds) : CountdownWidget(secdonds) {
    startButton->installEventFilter(parent);
 }

CountdownWidget::~CountdownWidget()
{
}

void CountdownWidget::startCountdown()
{
    bool ok;
    remainingSeconds = inputEdit->text().toInt(&ok);
    if (ok) {
        countdownTimer->setInterval(1000);
        countdownTimer->start();
    } else {
        // 输入错误处理，这里可以弹出提示框等
        countdownLabel->setText("输入错误，请输入整数");
    }
}

void CountdownWidget::updateCountdown()
{
    remainingSeconds--;
    if (remainingSeconds < 0) {
        countdownTimer->stop();
        countdownLabel->setText("倒计时结束");
        QMessageBox::warning(this, "提醒", "倒计时结束");
    } else {
        countdownLabel->setText(QString::number(remainingSeconds));
    }
}

void CountdownWidget::ResetCounter(int seconds) {
    remainingSeconds = seconds; 
    countdownLabel->setText(QString::number(remainingSeconds));
    countdownTimer->stop();
}

void CountdownWidget::RestartCounter() {
    startCountdown();
}